<template>
  <el-button 
    text 
    class="theme-toggle-btn"
    @click="toggleTheme"
    :title="isDark ? '切换到浅色模式' : '切换到深色模式'"
  >
    <el-icon>
      <Sunny v-if="isDark" />
      <Moon v-else />
    </el-icon>
  </el-button>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Sunny, Moon } from '@element-plus/icons-vue'
import { getCurrentTheme, setTheme, type ThemeMode } from '../../utils/theme'

// 主题切换相关
const currentTheme = ref<ThemeMode>(getCurrentTheme())
const isDark = computed(() => {
  if (currentTheme.value === 'auto') {
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }
  return currentTheme.value === 'dark'
})

// 主题切换方法
const toggleTheme = () => {
  const newTheme: ThemeMode = isDark.value ? 'light' : 'dark'
  console.log('ThemeToggle: 切换主题', { from: currentTheme.value, to: newTheme })
  currentTheme.value = newTheme
  setTheme(newTheme)
}

// 监听主题变化事件
const handleThemeChange = (event: CustomEvent) => {
  console.log('ThemeToggle: 收到主题变化事件', event.detail)
  currentTheme.value = event.detail.theme
}

onMounted(() => {
  // 监听全局主题变化事件
  window.addEventListener('theme-changed', handleThemeChange as EventListener)
  
  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  const handleSystemThemeChange = () => {
    if (currentTheme.value === 'auto') {
      // 触发重新计算
      currentTheme.value = 'auto'
    }
  }
  mediaQuery.addEventListener('change', handleSystemThemeChange)
  
  // 初始化时同步当前主题状态
  currentTheme.value = getCurrentTheme()
  console.log('ThemeToggle mounted:', { currentTheme: currentTheme.value, isDark: isDark.value })
})

onUnmounted(() => {
  window.removeEventListener('theme-changed', handleThemeChange as EventListener)
})
</script>

<style scoped>
/* 主题切换按钮样式 */
.theme-toggle-btn {
  padding: 10px;
  border-radius: 50%;
  transition: all 0.3s ease;
  color: #667eea;
  background: rgba(102, 126, 234, 0.1);
  border: 1px solid rgba(102, 126, 234, 0.2);
  backdrop-filter: blur(10px);
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.theme-toggle-btn:hover {
  background: rgba(102, 126, 234, 0.2);
  color: #5a67d8;
  transform: scale(1.1) rotate(15deg);
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.theme-toggle-btn .el-icon {
  font-size: 20px;
}

/* 深色模式下的主题切换按钮 */
:global(.dark) .theme-toggle-btn {
  background: rgba(102, 126, 234, 0.2);
  border-color: rgba(102, 126, 234, 0.3);
  color: #818cf8;
}

:global(.dark) .theme-toggle-btn:hover {
  background: rgba(102, 126, 234, 0.3);
  border-color: #818cf8;
  color: #a5b4fc;
  box-shadow: 0 4px 15px rgba(129, 140, 248, 0.4);
}
</style>
